Component({
  properties: {
    // 形状，circle或rectangle
    shape: {
      type: String,
      value: 'circle',
      observer: function (newVal) {
        if (newVal !== 'circle' && newVal !== 'rectangle') {
          console.warn('shape属性只能是circle或rectangle');
          this.setData({ shape: 'circle' });
        }
      }
    },

    width: {
      type: Number,
      value: 50
    },

    height: {
      type: Number,
      value: 50
    },

    // 初始位置x坐标
    initX: {
      type: Number,
      value: 20
    },
    // 初始位置y坐标
    initY: {
      type: Number,
      value: 100
    },
    // 背景颜色
    color: {
      type: String,
      value: '#07C160'
    },
    // 是否可拖动
    draggable: {
      type: Boolean,
      value: true
    },

    opacity: {
      type: Number,
      value: 0.3
    }
  },

  data: {
    x: 0,
    y: 0,
    width: 50,
    height: 50,
    isDragging: false,
    startX: 0,
    startY: 0,
    opacity: 0.3
  },

  lifetimes: {
    attached: function () {
      // 获取系统信息，用于边界检查
      this.systemInfo = wx.getWindowInfo();

      // 初始化位置
      this.setData({
        x: this.properties.initX,
        y: this.systemInfo.windowHeight - 160,
        width: this.properties.width,
        height: this.properties.height
      });
    }
  },

  methods: {
    handleTouchStart(e) {
      if (!this.properties.draggable) return;

      const touch = e.touches[0];
      this.setData({
        isDragging: true,
        startX: touch.clientX - this.data.x,
        startY: touch.clientY - this.data.y,
        opacity: 0.8
      });
    },

    handleTouchMove(e) {
      if (!this.properties.draggable || !this.data.isDragging) return;

      const touch = e.touches[0];
      let x = touch.clientX - this.data.startX;
      let y = touch.clientY - this.data.startY;

      // 边界检查
      if (this.systemInfo) {
        const maxX = this.systemInfo.windowWidth - 50; // 假设宽度为50px
        const maxY = this.systemInfo.windowHeight - 50; // 假设高度为50px

        x = Math.max(0, Math.min(x, maxX));
        y = Math.max(0, Math.min(y, maxY));
      }

      this.setData({
        x: x,
        y: y
      });

      // 触发拖动事件
      this.triggerEvent('drag', { x, y });
    },

    handleTouchEnd() {
      if (!this.properties.draggable) return;

      this.setData({
        isDragging: false,
        opacity: 0.3
      });

      // 触发拖动结束事件
      this.triggerEvent('dragend', { x: this.data.x, y: this.data.y });
    },

    handleTap(e) {
      this.triggerEvent('click');
    },

    // 外部调用的方法：设置位置
    setPosition(x, y) {
      this.setData({ x, y });
    },

    // 外部调用的方法：获取当前位置
    getPosition() {
      return { x: this.data.x, y: this.data.y };
    }
  }
});